#!/usr/bin/env python2
# ----------------------------------------------------------------------------
# Scans through QUEUE_IN and checks lines that haven't yet been received.
# To save on packets, want requests are concatenated.

import os, zlib, time, sys
import site_config as cfg
import qrpbbb_lib as lib

###

(packetsout, lineswanted, wants) = (0, 0, [])

print "\nqrpbbb_iwant.py executing at:", time.ctime()

pri = 200
if len(sys.argv) == 2:
    try:
        pri = int(sys.argv[1])
        print "Marking packets with priority",pri
    except:
        pri = 201
print

###

now = time.time()

for f in lib.queuein_filelist():
    name = os.path.basename(f)
    contenthash = lib.message_hash(lib.fetch_messagetext(f))
    if contenthash == name:
        # completed already
        continue

    # check mtime and ignore if a good chance of still being received
    minage = cfg.LIMITS[cfg.RADIOMODE]["WANTMINAGE"]
    if (now - os.path.getmtime(f)) < minage*60:
        continue

    message = lib.fetch_message(f)

    li = []
    for i in range(1, len(message)+1):
        if message.get(i) and message[i] == -1:
            li.append(i)
            lineswanted += 1

    for l in lib.linespec_split(li):
        wants.append (name + "," + l)

###

while len(wants) > 0:
    s = cfg.APRSPREAM + "W"
    while len(wants) > 0 and len(s) < 128:
        s += ":" + wants[0]
        wants = wants[1:]
    lib.packetout(s, priority=pri)
    packetsout += 1

if (lineswanted):
    print "Needing to retrieve",lineswanted,"lines."
if (packetsout):
    print "Packets generated:", packetsout

#
# ----------------------------------------------------------------------------
#
